from ubluetooth import BLE
import ubluetooth
import neopixel
from machine import Pin
import micropython

pin = Pin(8, Pin.OUT)
np = neopixel.NeoPixel(pin, n=3,bpp=3,timing=1)
ble = BLE() #创建ble对象
ble.active(True) #打开ble

Server_1_UUID = ubluetooth.UUID(0x181A)
Char_A_UUID = ubluetooth.UUID(0x2A6E)
Char_B_UUID = ubluetooth.UUID(0x2A6F)

Server_2_UUID = ubluetooth.UUID(0x9010)
Char_C_UUID = ubluetooth.UUID(0x9011)
Char_D_UUID = ubluetooth.UUID(0x9012)

#特性设置 元组
Char_A = (Char_A_UUID, ubluetooth.FLAG_READ)
Char_B = (Char_B_UUID, ubluetooth.FLAG_READ | ubluetooth.FLAG_WRITE | ubluetooth.FLAG_NOTIFY, )
Char_C = (Char_C_UUID, ubluetooth.FLAG_WRITE | ubluetooth.FLAG_NOTIFY)
Char_D = (Char_D_UUID, ubluetooth.FLAG_READ | ubluetooth.FLAG_WRITE)

#将特性放入服务
Server_1 = (Server_1_UUID, (Char_A, Char_B, ), )
Server_2 = (Server_2_UUID, (Char_C, Char_D, ), )
#将服务放入 服务集 中
ServersSet = (Server_1, Server_2, )
#注册服务集
((char_a, char_b, ), (char_c, char_d, ), ) = ble.gatts_register_services(ServersSet)

ble.gatts_write(char_a, b'\x24\x10')
ble.gatts_write(char_b, b'\x34\x12')

#广播
ble.gap_advertise(100, adv_data = b'\x02\x01\x05\x03\x09\x31\x32', resp_data = b'\x05\xFF\x01\x02\x03\x04')
def led(data):
    if data == 1:
        np[0] = (255, 0, 255)
        np.write()
    elif data == 0:
        np[0] = (0, 0, 0)
        np.write()
led(0)

def ble_irq(event, data):
    global conn_handle_global
    if event == 1:
        conn_handle = data[0]
        conn_handle_global = conn_handle
        print(conn_handle_global)
    elif event == 2:
        ble.gap_advertise(100, adv_data = b'\x02\x01\x05\x03\x09\x31\x32', resp_data = b'\x05\xFF\x01\x02\x03\x04')
    elif event == 3: #write
        conn_handle, char_handle = data
        buffer = ble.gatts_read(char_handle)
        print(buffer)
        if buffer == b'a':
            if conn_handle_global is not None:
                ble.gatts_notify(conn_handle_global, char_handle, b'b')
        elif buffer == b'1':
            led(1)
        elif buffer == b'0':
            led(0)
ble.irq(ble_irq)

